/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import ru.irenproject.BaseProtos.ReferenceType;
import ru.irenproject.store.Store;

import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.Message;

public final class Session {
  private final Store fStore;
  private final ProtoRegistry fProtoRegistry;
  private Map<ByteString, Message> fShapes = new HashMap<>();
  private Map<ByteString, Message> fSentShapes = new HashMap<>();

  public Session(Store store, ProtoRegistry protoRegistry) {
    fStore = store;
    fProtoRegistry = protoRegistry;
  }

  public void getUnsentShapes(Map<? super ByteString, ? super Message> changed,
      Collection<? super ByteString> deleted) {
    MapDifference<ByteString, Message> diff = Maps.difference(fSentShapes, fShapes);

    changed.putAll(diff.entriesOnlyOnRight());
    for (Map.Entry<ByteString, ValueDifference<Message>> e : diff.entriesDiffering().entrySet()) {
      changed.put(e.getKey(), e.getValue().rightValue());
    }

    deleted.addAll(diff.entriesOnlyOnLeft().keySet());

    fSentShapes = fShapes;
  }

  public void render(Collection<ByteString> mustRenderIds) {
    Map<ByteString, Message> newShapes = new HashMap<>();

    Queue<ByteString> pending = new ArrayDeque<>();
    pending.add(Store.ROOT_ID);

    while (!pending.isEmpty()) {
      ByteString id = pending.remove();
      if (!newShapes.containsKey(id)) {
        Message shape = mustRenderIds.contains(id) ? null : fShapes.get(id);
        if (shape == null) {
          shape = ((Visual) fStore.getThing(id)).render();
          fProtoRegistry.checkIsShape(shape.getDescriptorForType());
        }
        newShapes.put(id, shape);

        addShapeReferences(shape, pending);
      }
    }

    fShapes = newShapes;
  }

  private static void addShapeReferences(Message shape, Queue<ByteString> out) {
    for (FieldDescriptor fd : shape.getDescriptorForType().getFields()) {
      if (fd.getType() == Type.MESSAGE) {
        for (Object m : getFieldValues(shape, fd)) {
          addShapeReferences((Message) m, out);
        }
      } else if (isShapeReference(fd)) {
        for (Object id : getFieldValues(shape, fd)) {
          out.add((ByteString) id);
        }
      }
    }
  }

  private static boolean isShapeReference(FieldDescriptor fd) {
    return fd.getOptions().getExtension(BaseProtos.ref) == ReferenceType.SHAPE;
  }

  private static List<?> getFieldValues(Message message, FieldDescriptor fd) {
    if (fd.isRepeated()) {
      return (List<?>) message.getField(fd);
    } else if (message.hasField(fd)) {
      return Collections.singletonList(message.getField(fd));
    } else {
      return Collections.emptyList();
    }
  }

  public boolean hasShapeId(ByteString id) {
    return fShapes.containsKey(id);
  }
}
